using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlServerCe;
using Microsoft.WindowsMobile.Status;

namespace FeedFly
{
    /// <summary>
    /// Form for choosing a folder for a new folder or feed. 
    /// </summary>
    public partial class FolderSelectForm : Form
    {
        private Stack<SelectedFolder> folderStack = new Stack<SelectedFolder>(2);
        private FolderBrowseInterface parentForm;

        private SystemState OrientationWatcherState;

        public FolderSelectForm()
        {
            InitializeComponent();

            // set up oritentation monitoring
            OrientationWatcherState = new SystemState(SystemProperty.DisplayRotation);
            OrientationWatcherState.Changed += new ChangeEventHandler(OrientationChanged);
        }

        private void FolderSelectForm_Load(object sender, EventArgs e)
        {
            // load root folder by default
            SelectedFolder sf = new SelectedFolder(1, "Home", 0);
            sf.BreadCrumbs = sf.Name;
            LoadFolder(sf);
            folderListView.Focus();

            // form is starting in landscape mode, so shrink listview control
            if (SystemState.DisplayRotation != 0 && folderListView.Height == 240)
                folderListView.Height -= 80;
        }

        private void OrientationChanged(object sender, ChangeEventArgs args)
        {
            if ((int)args.NewValue == 0)
                folderListView.Height += 80; // portrait mode
            else
                folderListView.Height -= 80; // landscape mode
        }

        public void PrepareForm(FolderBrowseInterface parent)
        {
            parentForm = parent;
        }

        private void LoadFolder(SelectedFolder f)
        {
            // change cursor to WaitCursor
            Cursor.Current = Cursors.WaitCursor;

            // remove existing items
            if(folderListView.Items.Count > 0)
                folderListView.Items.Clear();

            folderListView.BeginUpdate();

            loadFolders(Folder.GetFolderDataReader(f.Id));

            // add new folder to stack if not already there
            if(folderStack.Count == 0)
                folderStack.Push(f);                
            else
            {
                if (!folderStack.Contains(f))
                {
                    f.BreadCrumbs = folderStack.Peek().BreadCrumbs + " > " + f.Name;
                    folderStack.Push(f);
                }
            }

            // update title
            folderNameLabel.Text = f.Name;

            // reset selection to previous selected folder
            if (folderListView.Items.Count > 0)
            {
                ListViewItem focusItem;

                if (folderListView.Items.Count < f.SelectedIndex + 1)
                    focusItem = folderListView.Items[0];
                else
                    focusItem = folderListView.Items[f.SelectedIndex];

                focusItem.Focused = true;
                focusItem.Selected = true;
                selectFolderContextMenuItem.Enabled = true;
                openMenuItem.Enabled = true;
            }
            else
            {
                selectFolderContextMenuItem.Enabled = false;
                openMenuItem.Enabled = false;
            }

            folderListView.EndUpdate();

            goBackPictureBox.Visible = folderStack.Count > 1;
            goBackMenuItem.Enabled = goBackPictureBox.Visible;

            // change cursor back to default
            Cursor.Current = Cursors.Default;
        }

        private void loadFolders(SqlCeDataReader rdr)
        {
            ListViewItem newItem;
            string[] columns = new string[2];

            while (rdr.Read())
            {                
                columns[0] = rdr.GetString(1);               
                columns[1] = rdr.GetInt32(0).ToString();               
                newItem = new ListViewItem(columns);
                newItem.ImageIndex = 0;
                folderListView.Items.Add(newItem);
            }

            rdr.Close();
            rdr.Dispose();
        }

        private void feedListView_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)            
            {
                case Keys.Enter:
                case Keys.Right:   
                case Keys.LButton:
                    viewItem();
                    break;
                case Keys.Left:
                    goBack();
                    break;
            }
        }

        private void goBack()
        {
            if (folderStack.Count > 1)
            {
                folderStack.Pop();
                LoadFolder(folderStack.Peek());
            }
        }

        private void viewItem()
        {
            ListViewItem currentItem;

            try
            {
                currentItem = folderListView.FocusedItem;
            }
            catch
            {
                return;
            }
              
            // set current index before loading another folder
            SelectedFolder f = folderStack.Pop();
            f.SelectedIndex = currentItem.Index;
            folderStack.Push(f);
            LoadFolder(new SelectedFolder(Convert.ToInt32(currentItem.SubItems[1].Text), currentItem.SubItems[0].Text, 0));

        }

        private void feedListView_ItemActivate(object sender, EventArgs e)
        {
            viewItem();
        }

        private void cancelMenuItem_Click(object sender, EventArgs e)
        {
            parentForm.Show();
            Hide();
        }

        private void openMenuItem_Click(object sender, EventArgs e)
        {
            viewItem();
        }

        private void goBackMenuItem_Click(object sender, EventArgs e)
        {
            goBack();
        }

        private void goBackPictureBox_Click(object sender, EventArgs e)
        {
            goBack();
        }

        private void goBackPictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            toggleGoBackButton(true);
        }

        private void goBackPictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            toggleGoBackButton(false);

            if (folderStack.Count < 2)
                goBackPictureBox.Visible = false;
        }

        private void toggleGoBackButton(bool selected)
        {
            goBackPictureBox.Visible = !selected;
            goBackPictureBoxSelected.Visible = selected;
        }

        private void selectMenuItem_Click(object sender, EventArgs e)
        {
            SelectedFolder f = folderStack.Peek();
            SelectFolder(f.Id, f.Name, f.BreadCrumbs);
        }

        private void SelectFolder(int folderId, string folderName, string breadCrumbs)
        {
            parentForm.FolderChosen(folderId, folderName, breadCrumbs);            
            parentForm.Show();

            // reduce stack back to root folder
            while(folderStack.Count > 1)
                folderStack.Pop();

            // restore root folder
            LoadFolder(folderStack.Peek());

            Hide();           
        }

        private void selectFolderContextMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = folderListView.FocusedItem;
            string folderName = selectedItem.SubItems[0].Text;

            SelectFolder(Convert.ToInt32(selectedItem.SubItems[1].Text), folderName,
                folderStack.Peek().BreadCrumbs + " > " + folderName); 
        }

    }
}